import { DbDataResult } from "./class"
import *  as db from "./db"
import { syncToCdn } from "../tool/tool"

/* 保存icon */
function saveIcon (appId, icon, channelName, platform) {
    return new Promise(async (resolve, reject) => {

        const sqlStr = "insert ignore icon(appId,icon,channelName,platform) values (?,?,?,?)"
        const params = [appId, icon, channelName, platform]

        try {
            await db.Query(sqlStr, params)
            resolve()
        } catch (error) {
            reject(error)
        }

        /* db.query(sqlStr, params, err => {
            if (err) {
                reject(err)
            }
            resolve()
        }) */
    })
}




/* 从数据库中取出对应的iconList，组装成app的iconMap */
export function getIconMap (channelName, platform) {
    return new Promise(async (resolve, reject) => {

        const sqlStr = "select appId from icon where channelName = ? and platform = ?"
        const params = [channelName, platform]

        try {

            const results = await db.Query(sqlStr,params)

            const resMap = results.reduce((prev,item) =>{
                prev[item.appId] = 1
                return prev
            },{})
            
            resolve(resMap)

        } catch (error) {

            reject(error)
            
        }

       /*  db.query(sqlStr, params, (err, results) => {
            if (err) {
                reject(err)
            }
            let res = {}
            results.forEach(r => {
                res[r.appId] = 1
            })
            resolve(res)
        }) */
    })
}

/* 保存数据 */
export function saveData (data) {
    return new Promise(async (resolve, reject) => {
        if (data.constructor != DbDataResult) {
            reject(new Error("db saveData error,err=参数类型错误，class 应为 DbDataResult"))
        }
        try {
            // 开启事务
            await db.BeginTransaction()

            ////删除旧数据
            const sqlStr = "delete from rankdata where channelName = ? and rankType = ? and `date` = ? and classify = ?"
            const params = [data.ChannelName, data.RankType, data.Date, data.Classify]
            await db.Query(sqlStr, params)

            // 插入新数据
            for (let i = 0; i < data.Data.length; i++) {
                const v = data.Data[i]
                const sqlStr = "insert into rankdata(appId,gameDesc,gameName,gameVersion,onSaleDate,playCount,typeName,rankType,dIndex,`date`,channelName,platform,bRank,downloadNum,score,company,classify,totalDownloadCount,commentCount,originalUrl) values (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)"
                const params = [v.AppId, v.GameDesc, v.GameName, v.GameVersion, v.OnSaleDate, v.PlayCount, v.TypeName, data.RankType, v.DIndex, data.Date, data.ChannelName, data.Platform, v.BRank, v.DownloadNum, v.Score, v.Company, v.Classify, v.TotalDownloadCount, v.CommentCount, v.OriginalUrl]

                // 插入
                await db.Query(sqlStr,params)

                // 保存icon
                if (v.Icon != "") {
                   await saveIcon(v.AppId, v.Icon, data.ChannelName, data.Platform)
                }

                // 插入首次录入表
                const sqlStr2 = "insert ignore firstcollecttime(appId,channelName,platform,firstcollecttime) values (?,?,?,?)"
                const params2 = [v.AppId, data.ChannelName, data.Platform, data.Date]
                await db.Query(sqlStr2,params2)


            }

            // 提交事务
            await db.Commit()

            // 同步cdn
            await syncToCdn()
           
            resolve()

        } catch (error) {
            // 回滚
            db.Rollback()
            reject(new Error("db saveData error,err=" + error))
        }

        /* db.beginTransaction(err1 => {
            if (err1) {
                reject(new Error("db saveData error2,err=" + err1))
            } else {
                //删除旧数据
                const sqlStr = "delete from rankdata where channelName = ? and rankType = ? and `date` = ? and classify = ?"
                const params = [data.ChannelName, data.RankType, data.Date, data.Classify]
                db.query(sqlStr, params, async (err2) => {
                    if (err2) {
                        db.rollback()
                        reject(new Error("db saveData error3,err=" + err2));
                    } else {
                        // 插入新数据
                        for (let i = 0; i < data.Data.length; i++) {
                            let v = data.Data[i]
                            let sqlStr = "insert into rankdata(appId,gameDesc,gameName,gameVersion,onSaleDate,playCount,typeName,rankType,dIndex,`date`,channelName,platform,bRank,downloadNum,score,company,classify,totalDownloadCount,commentCount,originalUrl) values (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)"
                            let params = [v.AppId, v.GameDesc, v.GameName, v.GameVersion, v.OnSaleDate, v.PlayCount, v.TypeName, data.RankType, v.DIndex, data.Date, data.ChannelName, data.Platform, v.BRank, v.DownloadNum, v.Score, v.Company, v.Classify, v.TotalDownloadCount, v.CommentCount, v.OriginalUrl]

                            db.query(sqlStr, params, (err3) => {
                                if (err3) {
                                    db.rollback()
                                    reject(new Error("db saveData error4,err=" + err3));
                                }
                            })


                            // 保存icon
                            if (v.Icon != "") {
                                saveIcon(v.AppId, v.Icon, data.ChannelName, data.Platform).catch(err4 => {
                                    reject(new Error("db saveIcon error5,err=" + err4));
                                })
                            }

                            // 插入首次录入表
                            const sqlStr2 = "insert ignore firstcollecttime(appId,channelName,platform,firstcollecttime) values (?,?,?,?)"
                            const params2 = [v.AppId, data.ChannelName, data.Platform, data.Date]
                            db.query(sqlStr2, params2, (err3) => {
                                if (err3) {
                                    db.rollback()
                                    reject(new Error("db saveData error8,err=" + err3));
                                }
                            })

                        }
                        db.commit(err5 => {
                            if (err5) {
                                reject(new Error("db saveData error6,err=" + err5));
                            }
                        })
                        // 同步cdn
                        try {
                            await syncToCdn()
                        } catch (err6) {
                            reject(new Error("db saveData error7,err=" + err6))
                        }
                        resolve()
                    }
                })



            }
        }) */
    })

}

